import React, { useState, useEffect } from 'react';
import {
  Container,
  Box,
  Typography,
  TextField,
  Button,
  Paper,
  CircularProgress,
  Stepper,
  Step,
  StepLabel,
  Divider,
  Select,
  MenuItem,
  FormControl,
  InputLabel
} from '@mui/material';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import axios from 'axios';
import config from './config';

const API_URL = config.API_URL;

function App() {
  const [sessionId, setSessionId] = useState(null);
  const [currentQuestion, setCurrentQuestion] = useState(null);
  const [answer, setAnswer] = useState('');
  const [feedback, setFeedback] = useState('');
  const [loading, setLoading] = useState(false);
  const [activeStep, setActiveStep] = useState(0);
  const [schools, setSchools] = useState([]);
  const [selectedSchool, setSelectedSchool] = useState('');

  const steps = ['选择学校', '开始面试', '回答问题', '查看反馈'];

  useEffect(() => {
    // 获取学校列表
    const fetchSchools = async () => {
      try {
        const response = await axios.get(`${API_URL}/schools`);
        setSchools(response.data);
      } catch (error) {
        console.error('获取学校列表失败:', error);
      }
    };
    fetchSchools();
  }, []);

  const startInterview = async () => {
    if (!selectedSchool) {
      alert('请选择学校');
      return;
    }

    try {
      setLoading(true);
      const response = await axios.post(`${API_URL}/start-interview`, {
        schoolId: selectedSchool
      });
      setSessionId(response.data.sessionId);
      setCurrentQuestion(response.data);
      setActiveStep(2);
    } catch (error) {
      console.error('开始面试失败:', error);
      alert(error.response?.data?.error || '开始面试失败');
    } finally {
      setLoading(false);
    }
  };

  const submitAnswer = async () => {
    try {
      setLoading(true);
      const response = await axios.post(`${API_URL}/submit-answer`, {
        sessionId,
        answer
      });
      setFeedback(response.data.feedback);
      setActiveStep(3);
    } catch (error) {
      console.error('提交答案失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const renderFeedback = (feedback) => {
    if (!feedback) return null;

    return (
      <Paper sx={{ p: 3, mb: 3 }}>
        <Typography variant="h6" gutterBottom>
          面试回顾
        </Typography>
        <Divider sx={{ mb: 2 }} />
        
        {/* 面试问题 */}
        <Box sx={{ mb: 3 }}>
          <Typography variant="subtitle1" color="primary" gutterBottom>
            面试问题：
          </Typography>
          <Typography variant="body1" sx={{ pl: 2, borderLeft: '4px solid #1976d2' }}>
            {currentQuestion.question}
          </Typography>
        </Box>

        {/* 考生回答 */}
        <Box sx={{ mb: 3 }}>
          <Typography variant="subtitle1" color="primary" gutterBottom>
            你的回答：
          </Typography>
          <Typography variant="body1" sx={{ pl: 2, borderLeft: '4px solid #2e7d32' }}>
            {answer}
          </Typography>
        </Box>

        {/* AI反馈 */}
        <Box>
          <Typography variant="subtitle1" color="primary" gutterBottom>
            AI 反馈：
          </Typography>
          <Box className="markdown-body">
            <ReactMarkdown remarkPlugins={[remarkGfm]}>{feedback}</ReactMarkdown>
          </Box>
        </Box>
      </Paper>
    );
  };

  return (
    <Container maxWidth="md">
      <Box sx={{ my: 4 }}>
        <Typography variant="h3" component="h1" gutterBottom align="center">
          AI 智能面试系统
        </Typography>

        <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
          {steps.map((label) => (
            <Step key={label}>
              <StepLabel>{label}</StepLabel>
            </Step>
          ))}
        </Stepper>

        {activeStep === 0 && (
          <Paper sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom>
              请选择目标学校
            </Typography>
            <FormControl fullWidth sx={{ mt: 2 }}>
              <InputLabel>学校</InputLabel>
              <Select
                value={selectedSchool}
                label="学校"
                onChange={(e) => setSelectedSchool(e.target.value)}
              >
                {schools.map((school) => (
                  <MenuItem key={school.id} value={school.id}>
                    {school.name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <Button
              variant="contained"
              onClick={() => setActiveStep(1)}
              disabled={!selectedSchool}
              sx={{ mt: 2 }}
            >
              下一步
            </Button>
          </Paper>
        )}

        {activeStep === 1 && (
          <Paper sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom>
              欢迎参加 AI 智能面试
            </Typography>
            <Typography variant="body1" paragraph>
              系统将随机抽取一道面试题，请认真思考后作答。
            </Typography>
            <Button
              variant="contained"
              onClick={startInterview}
              disabled={loading}
              sx={{ mt: 2 }}
            >
              {loading ? <CircularProgress size={24} /> : '开始面试'}
            </Button>
          </Paper>
        )}

        {activeStep === 2 && currentQuestion && (
          <Paper sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom>
              面试问题
            </Typography>
            <Typography variant="body1" paragraph>
              {currentQuestion.question}
            </Typography>
            <TextField
              fullWidth
              multiline
              rows={4}
              label="你的回答"
              value={answer}
              onChange={(e) => setAnswer(e.target.value)}
              margin="normal"
            />
            <Box sx={{ mt: 2 }}>
              <Button
                variant="contained"
                onClick={submitAnswer}
                disabled={loading || !answer}
              >
                {loading ? <CircularProgress size={24} /> : '提交答案'}
              </Button>
            </Box>
            {loading && (
              <Box sx={{ mt: 2, display: 'flex', alignItems: 'center' }}>
                <CircularProgress size={20} sx={{ mr: 1 }} />
                <Typography variant="body2" color="textSecondary">
                  AI 正在思考中，请稍候...
                </Typography>
              </Box>
            )}
          </Paper>
        )}

        {activeStep === 3 && (
          <>
            {renderFeedback(feedback)}
            <Box sx={{ mt: 2, display: 'flex', justifyContent: 'center' }}>
              <Button
                variant="contained"
                onClick={() => {
                  setSessionId(null);
                  setCurrentQuestion(null);
                  setAnswer('');
                  setFeedback('');
                  setActiveStep(0);
                }}
              >
                重新开始
              </Button>
            </Box>
          </>
        )}
      </Box>
    </Container>
  );
}

export default App;
